<template>
  <ContentWrap>
    <el-row>
      <el-col :span="16">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="200px">
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="formData.userName" clearable placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="formData.workUnit" clearable placeholder="请输入工作单位" />
          </el-form-item>
          <el-form-item label="负责区域" prop="regionAddress">
            <el-select v-model="formData.regionAddress" multiple placeholder="请选择负责区域" clearable>
              <el-option v-for="item in provinceStore.provinceDate" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label=" ">
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="setClose()">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </ContentWrap>
</template>
<script lang="ts" setup>
import * as contactApi from '@/api/infoArrive/contacts/index'
import { useRoute } from 'vue-router'

defineOptions({ name: 'ContactsForm' })

import { useProvinceStore } from '@/store/modules/province'
const provinceStore = useProvinceStore()
const change = () => provinceStore.fetchProvinceData();
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData:any = ref({
  id: null,
  userName: '',
  phone: '',
  workUnit: '',
  regionAddress: [],
})

const formRules = reactive({
  userName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  phone: [
    {
      required: true,
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  workUnit: [{ required: true, message: '工作单位不能为空', trigger: 'blur' }],
  regionAddress: [{ required: true, message: '负责区域不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const route = useRoute()
const router = useRouter()
const id = route.query.id

const open = async (type, id) => {
  resetForm()
  formType.value = type
  await change()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await contactApi.getContacts(id)
      formData.value.regionAddress  =formData.value.regionAddress? formData.value.regionAddress.split(','):[]
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 提交表单 */
const emit = defineEmits(['success','setClose']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value == 'update') {
      await contactApi.saveContacts({ ...formData.value,regionAddress:formData.value.regionAddress.join(',') })
      message.success(t('common.createSuccess'))
    } else {
      await contactApi.saveContacts({ ...formData.value,regionAddress:formData.value.regionAddress.join(',') })
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    emit('success')
    setClose()
  } finally {
    formLoading.value = false
  }
}
const setClose = () => {
  emit('setClose')
}
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: null,
    userName: '',
    phone: '',
    workUnit: '',
    regionAddress: [],
  }
  formRef.value?.resetFields()
}

</script>
